package cn.ibizlab.eam.core.extensions.service;

import cn.ibizlab.eam.core.eam_core.filter.IBZSEQSearchContext;
import cn.ibizlab.eam.core.eam_core.service.impl.IBZSEQServiceImpl;
import cn.ibizlab.eam.core.util.helper.Aops;
import lombok.extern.slf4j.Slf4j;
import cn.ibizlab.eam.core.eam_core.domain.IBZSEQ;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Primary;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 实体[序列号] 自定义服务对象
 */
@Slf4j
@Primary
@Service("IBZSEQExService")
public class IBZSEQExService extends IBZSEQServiceImpl {

    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }

    /**
     * [GenId:获取Id] 行为扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public IBZSEQ genId(IBZSEQ et) {
        // 实体名称(必填)
        String entity = et.getEntity();
        // 前缀
        String prefix = et.getPrefix();
        // 参数
        String params = et.getParams();
        // 日期参数格式
        String dateFormat = et.getDateformat();
        // 日期 默认：当前时间
        Timestamp dateTime = et.getDatetime();
        if (dateTime == null) {
            dateTime = new Timestamp(System.currentTimeMillis());
        }
        // 序列号长度
        Integer serialLength = et.getSeriallength();
        // 自定义生成规则
        String seqformat = et.getSeqformat();
        // 后缀
        String suffix = et.getSuffix();
        // 生成规则 默认值type1
        String seqType = et.getSeqtype();

        // 当前ID
        String curId = "";

        // "实体"不为空，找到这条记录,生成相应id之后更新当前序列号,为空,新建一条记录
        if (entity != null && !entity.isEmpty()) {
            IBZSEQSearchContext ctx = new IBZSEQSearchContext();
            ctx.setN_entity_eq(entity);
            if (prefix != null) {
                ctx.setN_prefix_eq(prefix);
            }
            ctx.setSize(1);
            List<IBZSEQ> ibzseqList = this.searchDefault(ctx).getContent();

            // 当前实体生成id的记录不存在,新建一条记录
            if (ibzseqList.size() == 0) {
                IBZSEQ ibzseq = new IBZSEQ();
                //ibzseq.setIbzseqid(entity);
                ibzseq.setIbzseqname(entity);
                ibzseq.setEntity(entity);
                if (prefix != null) {
                    ibzseq.setPrefix(prefix.toUpperCase());
                }
                // 日期格式 默认YYMMDD
                dateFormat = dateFormat == null ? "yyMMdd" : dateFormat;
                ibzseq.setDateformat(dateFormat);
                // 序列号长度 默认4
                serialLength = serialLength == null ? 4 : serialLength;
                ibzseq.setSeriallength(serialLength);

                if (seqformat != null) {
                    ibzseq.setSeqformat(seqformat);
                }
                if (suffix != null) {
                    ibzseq.setSuffix(suffix.toUpperCase());
                }
                if (params != null) {
                    ibzseq.setParams(params);
                }
                seqType = seqType == null ? "type1" : seqType;
                ibzseq.setSeqtype(seqType);
                ibzseq.setCuroffset(0L); // 当前序列号

                // 根据规则获取相应的id值
                curId = genCurId(ibzseq, dateTime);
                Aops.getSelf(this).create(ibzseq);
            } else {
                //当前实体生成id的记录存在，查看是否生成规则发生变化，如果有变化，以变化后的为准
                IBZSEQ ibzseq = ibzseqList.get(0);
                // 当前需要的规则与数据库里面存储的规则不同，以当前需要的规则为准
                if (ibzseq.getSeqtype() != null) {
                    if (seqType != null && StringUtils.compare(ibzseq.getSeqtype(), seqType) != 0) {
                        ibzseq.setSeqtype(seqType);
                        if (prefix != null) {
                            ibzseq.setPrefix(prefix.toUpperCase()); // 前缀
                        }
                        if (dateFormat != null) {
                            ibzseq.setDateformat(dateFormat);// 日期格式
                        }
                        if (serialLength != null) {
                            ibzseq.setSeriallength(serialLength);// 序列号长度
                        }
                        if (seqformat != null) {
                            ibzseq.setSeqformat(seqformat); // 自定义生成规则
                        }
                        if (suffix != null) {
                            ibzseq.setSuffix(suffix.toUpperCase()); // 后缀
                        }
                        if (params != null) {
                            ibzseq.setSeqformat(params); // 参数
                        }
                    }
                    curId = genCurId(ibzseq, dateTime);
                    Aops.getSelf(this).update(ibzseq);
                }
            }
        }

        // 判断id是否生成成功
        if (!curId.isEmpty()) {
            et.setCurid(curId);
        }
        return super.genId(et);

    }

    /**
     * 获取对应格式的日期
     *
     * @param dateFormat
     * @return
     */
    private String genDate(String dateFormat, Timestamp dateTime) {
        String date = "";
        LocalDateTime localDateTime = dateTime.toLocalDateTime();
        // 判断当前需要的日期格式是哪一种,生成相应格式的日期编号 (yyyy-MM-dd HH:mm:ss)
        if (StringUtils.compare(dateFormat, "yyMMdd") == 0) {
            date = DateTimeFormatter.ofPattern("yyMMdd").format(localDateTime);
        }
        if (StringUtils.compare(dateFormat, "yyyyMMdd") == 0) {
            date = DateTimeFormatter.ofPattern("yyyyMMdd").format(localDateTime);
        }
        if (StringUtils.compare(dateFormat, "HHmmss") == 0) {
            date = DateTimeFormatter.ofPattern("HHmmss").format(localDateTime);
        }
        if (StringUtils.compare(dateFormat, "MMdd") == 0) {
            date = DateTimeFormatter.ofPattern("MMdd").format(localDateTime);
        }
        if (StringUtils.compare(dateFormat, "MMddHHmm") == 0) {
            date = DateTimeFormatter.ofPattern("MMddHHmm").format(localDateTime);
        }
        return date;
    }

    /**
     * 获取序列号
     *
     * @param ibzseq
     * @return
     */
    private String genCurOffset(IBZSEQ ibzseq) {
        String offset = "";
        // 如果当前序列号小于要求的序列号长度,进行左补0的操作
        if (ibzseq.getCuroffset().toString().length() < ibzseq.getSeriallength()) {
            offset = String.format("%0" + ibzseq.getSeriallength() + "d", ibzseq.getCuroffset() + 1);
        }
        // 获取新序列号之后,更新当前序列号
        ibzseq.setCuroffset(ibzseq.getCuroffset() + 1);
        return offset;
    }

    /**
     * 根据不同的规则，生成相应的Id
     *
     * @param ibzseq
     * @return
     */
    private String genCurId(IBZSEQ ibzseq, Timestamp dateTime) {
        String curId = "";

        // 规则1:前缀+日期格式+序列号 如:A+210122+0001
        if (StringUtils.compare("type1", ibzseq.getSeqtype()) == 0) {
            String date = genDate(ibzseq.getDateformat(), dateTime);
            String offset = genCurOffset(ibzseq);
            curId = ibzseq.getPrefix() + date + offset;
            return curId;
        }
        // 规则2:前缀+N位的序列号 如:"EN-"+000001(N=6)
        if (StringUtils.compare("type2", ibzseq.getSeqtype()) == 0) {
            String offset = genCurOffset(ibzseq);
            curId = ibzseq.getPrefix() + offset;
            return curId;
        }
        // 规则3:生成为N位的序列号 如：000001
        if (StringUtils.compare("type3", ibzseq.getSeqtype()) == 0) {
            curId = genCurOffset(ibzseq);
            return curId;
        }
        // 规则4:前缀+日期格式+序列号+后缀 如:A+210122+0001+B
        if (StringUtils.compare("type4", ibzseq.getSeqtype()) == 0) {
            String date = genDate(ibzseq.getDateformat(), dateTime);
            String offset = genCurOffset(ibzseq);
            curId = ibzseq.getPrefix() + date + offset + ibzseq.getSuffix();
            return curId;
        }
        // 规则5:前缀+序列号+后缀 如:A+0001+B
        if (StringUtils.compare("type5", ibzseq.getSeqtype()) == 0) {
            String offset = genCurOffset(ibzseq);
            curId = ibzseq.getPrefix() + offset + ibzseq.getSuffix();
            return curId;
        }
        // 规则6:自定义
        if (StringUtils.compare("definedRule", ibzseq.getSeqtype()) == 0) {
            if (StringUtils.compare("preAddCode", ibzseq.getSeqformat()) == 0) {
                curId = ibzseq.getPrefix() + ibzseq.getParams();
                return curId;
            }
            if (StringUtils.compare("empodetail", ibzseq.getSeqformat()) == 0) {
                String offset = genCurOffset(ibzseq);
                curId = ibzseq.getPrefix()+ibzseq.getParams() + offset;
                return curId;
            }
        }
        return curId;
    }

}

